<?php defined('SYSPATH') OR die('No direct access allowed.');

/**
 * Category model
 *
 * @package  Forum
 *
 */
class Forum_Category_Model extends ORM_MPTT implements Acl_Resource_Interface {

  protected $has_many = array('forum_posts', 'forum_users' => 'forum_moderated_category');
	//protected $db = 'forum';
	protected $reload_on_wakeup = FALSE;
	protected $foreign_key = array('forum_posts' => 'category_id');

  public function validate(array & $array, $save = FALSE) {
    $array = Validation::factory($array)
			->pre_filter('trim')
			->add_rules('title', 'required', 'length[3,100]', 'standard_text', array($this, 'name_available'))
			->add_rules('description', 'chars[\pL\pN\pZ\pP]', 'length[3,200]');

		return parent::validate($array, $save);
  }

  public function name_available($id) {
    return !$this->db
			->where($this->unique_key($id), $id)
			->count_records($this->table_name);
  }

	public function get_resource_id() {
		return 'forum_category';
	}

	public function unique_key($id)
	{
		if ( ! empty($id) AND is_string($id) AND ! ctype_digit($id))
		{
			return 'title';
		}

		return parent::unique_key($id);
	}

	public function increase_count($column, $value = 1) {
		if (!$this->loaded) return FALSE;
		if ((strlen($column)==0) OR (!array_key_exists($column."_count", $this->table_columns)))
			return FALSE;
		$column .= "_count";
		if ($value < 0) $value = "(".$value.")";
		$this->db->set($column, new Database_Expression($column.' + '.$value))
			->where($this->scope_column, $this->scope())
			->where($this->left_column." <= ".$this->left())
			->where($this->right_column." >= ".$this->right())
			->update($this->table_name);
	}

	public function is_moderated_by($user_id = NULL) {
		if (is_null($user_id)) return FALSE;
		if (! $this->loaded) return FALSE;
		return (in_array($user_id, $this->get_moderators()));
	}

	public function get_moderators($object = FALSE) {
		return ORM::factory('forum_moderated_category')->get_moderators($this, $object);
	}
}